package com.newgrand.annexserver.storage.service;

import com.newgrand.annexcommon.model.FileEntity;
import com.newgrand.annexcommon.utils.DateUtil;
import com.newgrand.annexcommon.utils.FileUtil;
import com.newgrand.annexserver.beans.Dbconfig;
import com.newgrand.annexserver.storage.StorageContextHolder;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

public class DefaultFileSystemStorage implements StorageService {

    private final static Logger logger = LoggerFactory.getLogger(DefaultFileSystemStorage.class);

    private String fileDir;

    public DefaultFileSystemStorage(Dbconfig dbconfig) {
        fileDir = dbconfig.getStoreUrl();
        logger.info("refresh file system {}", fileDir);
    }

    public String save(FileEntity entity) {
        String fileName = FileUtil.generateFileName(entity.getFileName());
        logger.info("save file system {}", fileName);

        byte[] data = entity.getData();
        String parentPath = DateUtil.getToday();
        File parentFile = new File(fileDir, parentPath);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        String filePath = parentPath + File.separator + fileName;
        File file = new File(parentFile, fileName);
        try {
            FileUtils.writeByteArrayToFile(file, data);
        } catch (Exception e) {
            logger.error("save " + fileName, e);
        }
        return filePath;
    }

    public String saveThumb(FileEntity entity) {
        entity.setFileName(FileUtil.getFsThumbFileName(entity.getFileName()));
        logger.info("save file system thumb {}", entity.getFileName());
        return save(entity);
    }

    @Override
    public FileEntity query(String id) {
        logger.info("query file system {}", id);
        File file = new File(fileDir, id);
        if (file.exists() && file.isFile()) {
            try {
                byte[] data = FileUtils.readFileToByteArray(file);
                return new FileEntity(data);
            } catch (Exception e) {
                logger.error("query " + id, e);
            }
        }
        return null;
    }


    @Override
    public void close() {
    }

    @Override
    public FileEntity queryThumb(String id) {
        logger.info("refresh file system {}, {}", fileDir, id);
        File file = new File(fileDir, id);
        if (file.exists() && file.isFile()) {
            try {
                String simpleName = FileUtil.getSimpleFileName(file.getName());
                int index = simpleName.lastIndexOf("_");
                if (index > -1) {
                    simpleName = simpleName.substring(0, index);
                }
                final String fName = simpleName;

                Path thumbFile = Files.list(file.getParentFile().toPath())
                        .filter(t -> t.toFile().isFile() && t.toFile().getName().startsWith(fName + "_thumb_"))
                        .findFirst()
                        .orElse(null);
                if (thumbFile != null) {
                    byte[] data = FileUtils.readFileToByteArray(thumbFile.toFile());
                    return new FileEntity(data);
                }
            } catch (Exception e) {
                logger.error("queryThumb " + id, e);
            }
        }
        return null;
    }


}
